<?php
namespace control;
/*
*跟进记录类
*/
class followClass extends adIndexClass
{
    private const title = '跟进记录';
    private const page = 'follow';
    public array $followTarget = ['线索','客户'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'manager'          => [
                        'name'  => "{l.follow.home.manager}",
                        'width' => 200,
                    ],
                    'target' => [
                        'name'  => "{l.follow.home.target}",
                        'width' => 200,
                    ],
                    'targetName'  => [
                        'name'  => "{l.follow.home.targetName}",
                        'width' => 200,
                    ],
                    'contactName'         => [
                        'name'  => '{l.follow.home.contactName}',
                        'width' => 200,
                    ],
                    'followType'          => [
                        'name'  => '{l.follow.home.followType}',
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => "{l.follow.home.text}",
                        'width' => 350,
                    ],
                    'time'          => [
                        'name'  => "{l.follow.home.time}",
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    L('follow.home.target') => select(array("name" => "target","option" => $this->followTarget)),
                    L('follow.home.targetName')   => text(array("name" => "targetName")),
                    L('follow.home.contactName') => text(array("name" => "contactName")),
                ],
                [
                    L('follow.home.followType')  => select(array("name" => "followType","option" =>explode("，", para("followQuick")))),
                    L('follow.home.text') => text(array("name" => "text")),
                    L('follow.home.timeQuantum') => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($this->power("follow", "seeAll")) {
            $array[0][] = [
                L('follow.home.manager') => selectMultiple(array('table' => 'staff', "class" => 'width200', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager'))
            ];
        }
        //生成查询表单
        $html = $this->tableShow($array,1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户管理-跟进记录-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户管理-跟进记录-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "contactName" => $this->post('contactName'),
            "targetName" => $this->post('targetName'),
            "text" => $this->post('text'),//跟进内容
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "target" => $this->post('target'),//对象
            "stid" => $this->post('stid'),//跟进员工
            "followType" => $this->post('followType'),
        );
        $and=" and target in ('".implode("','", $this->followTarget)."')";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }

        //如果没有查看所有员工订单的权限
        if (!$this->power("follow", "seeAll")) {
            $and .= " and stid = '".$this->control['stid']."' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like,"=" => $equal)).$and;
        $page = $this->page(array("table" => "follow","where" => $where,"order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $staff = query("staff", " stid = '$array[stid]' ");
                        $row[] = $staff['name'];
                        break;
                    case "text":
                        $text = preg_replace(array("/\n/"), array("<br>"), $array['text']);
                        $row[] = $text;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'].$button."<form name='listForm'>".$li."</form>".$page['button'].clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('follow.exportData.power');
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => 'follow',
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $staff = query("staff", " stid = '$array[stid]' ");
                $text = preg_replace(array("/\n/"), array("<br>"), $array['text']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '跟进人'=>$staff['name'],
                            '对象名称'=>$array['targetName'],
                            '联系人'=>$array['contactName'],
                            '跟进方式'=>$array['followType'],
                            '跟进内容'=>$text,
                            '跟进时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('follow.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('follow.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*行政人事-工作事务-跟进记录*/
    public function affairFollow()
    {
        $affair = query("affair", "id = '".$this->get('id')."'");
        if (empty($affair['id'])) {
            $json['html'] = L('follow.affairFollow.empty');
        } elseif ($affair['stid'] != $this->control['stid'] and !$this->power("affair", "seeAll")) {
            $json['html'] = L('follow.affairFollow.power');
        } else {
            $power = [];
            if ($this->power("affair", "followAdd")) {
                $power[] = "新增";
            }
            if ($this->power("affair", "followDel")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "事务","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }
    /*客户管理-客户列表-跟进记录*/
    public function clientRecord()
    {
        $kehu = query("kehu", "khid = '".$this->get('id')."'");
        if (empty($kehu['khid'])) {
            $json['html'] = L('follow.clientRecord.empty');
        } elseif (!in_array($this->control['stid'], explode(",", $kehu['see'])) and !$this->power("client", "seeAll")) {
            $json['html'] = L('follow.clientRecord.power');
        } else {
            $power = [];
            if ($this->power("client", "newFollow")) {
                $power[] = "新增";
            }
            if ($this->power("client", "delFollow")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "客户","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }
	/*客户管理-供应商列表-跟进记录*/
    public function supplierRecord()
    {
		$page = 'supplier';
		$table = 'supplier';
        $info = query($table, "id = '".$this->get('id')."'");
        if (empty($info['id'])) {
            $json['html'] = L('follow.supplierRecord.empty');
        } elseif ($this->control['stid'] != $info['stid'] and !$this->power($page, "seeAll")) {
            $json['html'] = L('follow.supplierRecord.power');
        } else {
            $power = [];
            if ($this->power($page, "edit")) {
                $power[] = "新增";
            }
            if ($this->power($page, "del")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "供应商", "targetId" => $this->get('id'), "power" => $power));
        }
        return json_encode($json, 320);
    }

    /*线索-跟进记录*/
    public function clueRecord()
    {
        $info = query("clue", "id = '".$this->get('id')."'");
        if (empty($info['id'])) {
            $json['html'] = L('follow.clueRecord.empty');
        } elseif (!in_array($this->control['stid'], explode(",", $info['see'])) and !$this->power("clue", "seeAll")) {
            $json['html'] = L('follow.clueRecord.power');
        } else {
            $power = [];
            if ($this->power("clue", "newFollow")) {
                $power[] = "新增";
            }
            if ($this->power("clue", "delFollow")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "线索","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }
    /*商机-跟进记录*/
    public function opportunityRecord()
    {
        $info = query("opportunity", "id = '".$this->get('id')."'");
        if (empty($info['id'])) {
            $json['html'] = L('follow.opportunityRecord.empty');
        } elseif (!in_array($this->control['stid'], explode(",", $info['see'])) and !$this->power("opportunity", "seeAll")) {
            $json['html'] = L('follow.opportunityRecord.power');
        } else {
            $power = [];
            if ($this->power("opportunity", "newFollow")) {
                $power[] = "新增";
            }
            if ($this->power("opportunity", "delFollow")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "商机","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }
    /*客户管理-订单列表-跟进记录*/
    public function orderRecord()
    {
        $buyCar = query("buycar", "id = '".$this->get('id')."'");
        if (empty($buyCar['id'])) {
            $json['html'] = L('follow.orderRecord.empty');
        } elseif ($buyCar['stid'] != $this->control['stid'] and !$this->power("order", "seeAll")) {
            $json['html'] = L('follow.orderRecord.power');
        } else {
            $power = [];
            if ($this->power("order", "newFollow")) {
                $power[] = "新增";
            }
            if ($this->power("order", "delFollow")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "订单","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }

    /*招聘管理-人才库-跟进记录*/
    public function talentRecord()
    {
        $talentPool = query("talent_pool", "id = '".$this->get('id')."'");
        if (empty($talentPool['id'])) {
            $json['html'] = L('follow.talentRecord.empty');
        } else {
            $power = [];
            if ($this->power("talentPool", "newFollow")) {
                $power[] = "新增";
            }
            if ($this->power("talentPool", "delFollow")) {
                $power[] = "删除";
            }
            $json['html'] = $this->follow(array("target" => "人才库","targetId" => $this->get('id'),"power" => $power));
        }
        return json_encode($json, 320);
    }



    /*项目管理-我的任务-跟进记录*/
    public function allotFollow()
    {
        $buyCarAllot = query("buycar_allot", " id = '".$this->get('id')."' ");
        $sql = find(array("table" => "follow","where" => " targetId = '$buyCarAllot[buyCarId]' order by time desc "));
        if ($sql['num'] == 0) {
            $json['html'] = L('follow.allotFollow.none');
        } else {
            $json['html'] = "";
            foreach ($sql['array'] as $array) {
                $json['html'] .= "<div class='record'>".neirong($array['text'])."\n<span class='gray'>".$array['time']."</span></div>";
            }
        }
        //返回
        return json_encode($json, 320);
    }
    /*跟进记录函数
    $data = array(
        "target" => "跟进对象",
        "targetid" => "对象ID",
        "power" => "权限数组",
    );
    */
    public function follow($data)
    {
        //跟进记录
        $follow = "";
        $sql = find(array("table" => "follow","where" => " targetId = '".$data['targetId']."' order by time desc "));
        if ($sql['num'] == 0) {
            $follow = "";
        } else {
            foreach ($sql['array'] as $array) {
                $del = "";
                if (in_array("删除", $data['power']) and $array['stid'] == $this->control['stid']) {
                    $del = "<a href='".root."control/adIndex.html?cla=follow&fun=followDel&id=".$array['id']."'><div class='followDel'>×</div></a>";
                }
                $staff = query("staff", " stid = '$array[stid]' ");
                $talent = query('talent_pool', "id = '$staff[talentId]'");
                if (mb_strlen($array['text'], "UTF8") < 68) {
                    $name = "";
                    $titleText = $array['text'];
                    $divText = "";
                } else {
                    $name = $staff['name'];
                    $titleText = "";
                    $divText = "
					<div class='followText'>
						".neirong($array['text'])."
					</div>
					";
                }
                $follow .= "
				<div class='followTitle'>
					<img src='".headImg($talent['sex'], $staff['ico'])."'>
					".$name.$titleText."
					<span>".$array['time']."</span>&nbsp;
					".$del."
				</div>
				".$divText;
            }
        }
        $follow = "<div class='follow' orderPageDiv='record'>".$follow."</div>";
        //新增跟进
        if (in_array("新增", $data['power'])) {
            $contactHtml=$workFlowTitle='';
            $workFlowArray = [];
            if ($data['target'] =='客户') {
                $workFlowTitle = L('follow.follow.workFlow');
                $workFlowArray = explode("，", para("clientWorkFlow"));
                $kehu = query('kehu', "khid = '{$data['targetId']}'");
                $all = find(array('table'=>'kehu_staff',"where"=>"khid = '{$data['targetId']}' order by time asc"));
                //把客户基本信息中的常用联系人添加到跟进中
                $option['frequent']=$kehu['contactName'];
                foreach ($all['array'] as $val) {
                    $option[$val['id']] = $val['name'];
                }
                $contactHtml = "<li><div>".must.L('follow.follow.contact').select(array('option'=>$option,'class'=>'select','name'=>'contactId','title'=>L('follow.follow.choice')))."</div></li>";
            } elseif ($data['target'] =='线索') {
                $workFlowArray = explode("，", para("clueWorkFlow"));
                $workFlowTitle = L('follow.follow.workFlow');
            } elseif ($data['target'] =='供应商') {
                $workFlowArray = explode("，", para("supplierWorkFlow"));
                $workFlowTitle = L('follow.follow.workFlow');
            } elseif ($data['target'] =='商机') {
                $workFlowTitle = L('follow.follow.possibility');
                $workFlowArray = explode("，", para("possibilityOption"));
                $contactHtml = "<li><div>".L('follow.follow.cause').select(array('class'=>'select','name'=>'reason','title'=>L('follow.follow.choice'),'option'=> explode("，", para("lostOpportunityOption"))))."</div></li>";
            }
            $plan = text(array("name" => "startDay","laydate" => [],"title" => "","class" => "text textPrice"));
            $quickArray = explode("，", para("followQuick"));
            $followQuick = "";
            foreach ($quickArray as $value) {
                $followQuick .= "<li onclick='followQuick(this)'>".$value."</li>";
            }

            $workFlowQuick = "";
            foreach ($workFlowArray as $value) {
                $workFlowQuick .= "<li onclick='workFlowQuick(this)'>".$value."</li>";
            }
            $followStyle='';
            if (in_array($data['target'], ['客户','线索','商机', '供应商'])) {
                $followStyle = "<li><span>".L('follow.follow.followQuick')."</span><ul id='followQuick' style='display: inline-flex' class='followQuick'>".$followQuick."</ul>";
            }
            $quickArray = explode("，",para("textQuick"));
            $textQuick = "";
            foreach($quickArray as $value){
                $textQuick .= "<li onclick='textQuick(this)'>".$value."</li>";
            }

            $new = "
			<div class='kuang' orderPageDiv='record'>
				<form name='followForm'>
				<textarea name='text' class='followTextarea' placeholder='".L('follow.follow.newFollow')."'></textarea>
				<input name='target' type='hidden' value='".$data['target']."'>
				<input name='targetId' type='hidden' value='".$data['targetId']."'>
				<ul class='followUl'>
				<li><ul  style='display: inline-flex' class='followQuick'>".$textQuick."</ul></li>
				{$contactHtml}
				<li><p>".L('follow.follow.nextFollowDate').$plan."</p></li>
				{$followStyle}
				<li><span>{$workFlowTitle}</span><ul  style='display: inline-flex' class='followQuick'>".$workFlowQuick."</ul></li>
				</ul>
				".hidden(array('name'=>'followType','value'=>'')).hidden(array('name'=>'workFlow','value'=>''))."
				</form>

				<div class='clear'></div>
				<input type='button' class='button' value='".L('follow.follow.sub')."' onclick=\"subForm('followForm',root+'control/adIndex.html?cla=follow&fun=add')\">
			</div>
			<style>
			.followUl>li{margin: 15px 5px}
</style>
			";
            $new.=<<<eof
<script>
 function followQuick(e){
     let val = $(e).text();
     $(e).parent().find("li").css('background-color',"#ccc");
     $(e).css('background-color','#9ED0FF');
     $("[name='followType']").val(val)
 }
  function workFlowQuick(e){
     let val = $(e).text();
     $(e).parent().find("li").css('background-color',"#ccc");
     $(e).css('background-color','#9ED0FF');
     $("[name='workFlow']").val(val)
 }
</script>
eof;
        }
        $new=$new??'';
        return $new.$follow;
    }
    /*客户管理-新增跟进记录*/
    public function add()
    {
        //赋值
        $finger=0;
        $url='';
        $targetCla = '';
        $targetFun = '';
        $backlogType = $this->post('target')."跟进";//待办事项类型
        $followText = $this->post('text')."【".$this->control['name']."】";//添加后缀，防止管理员被删除后无法通过管理员id查询到管理员姓名
        $date = date("Y-m-d");
        $field = array(
            "id" => suiji(),
            'coid'=>self::$coid,
            "stid" => $this->control['stid'],
            "target" => $this->post('target'),//跟进对象
            "targetId" => $this->post('targetId'),//跟进对象ID号
            "text" => $followText,
            "followType"=>$this->post('followType'),
            "time" => date("Y-m-d H:i:s"),//创建时间
        );
        //是否存在相同的下次跟进日期提醒计划
        $repeatNum = sqlNum("backlog", " stid = '".$this->control['stid']."' and type = '$backlogType' and typeId = '$field[targetId]' and startDay = '".$this->post('startDay')."' ");
        //当天是否提交相同内容的跟进信息
        $repeatTxt = sqlNum("follow", " stid = '".$this->control['stid']."' and target = '$field[target]' and targetId = '$field[targetId]' and text = '$followText' and time > '$date' ");
        //判断
        if (empty($field['target'])) {
            $json['warn'] = L('follow.add.objEmpty');
        } elseif (empty($field['targetId'])) {
            $json['warn'] = L('follow.add.idEmpty');
        } elseif (empty($this->post('text'))) {
            $json['warn'] = L('follow.add.contentEmpty');
        } elseif ($field['target'] =='客户' && empty($this->post('contactId'))) {
            $json['warn'] = L('follow.add.choiceContact');
        } elseif (!empty($this->post('startDay')) and $this->post('startDay') < $date) {
            $json['warn'] = L('follow.add.dateError');
        } elseif (!empty($this->post('startDay')) and $repeatNum > 0) {
            $json['warn'] = L('follow.add.dateRepeat');
        } elseif ($repeatTxt > 0) {
            $json['warn'] = L('follow.add.contentRepeat');
        } elseif ($field['target'] == "客户") {
            if (!$this->power("client", "newFollow")) {
                $json['warn'] = L('follow.add.clientPower');
            } else {
                $kehu = query("kehu", " khid = '$field[targetId]' ");
                if (empty($kehu['khid'])) {
                    $json['warn'] = L('follow.add.clientEmpty');
                } else {
                    $finger = 2;
                    //更新客户更新时间
                    update(array(
                        "table" => "kehu",
                        "field" => array("updateTime" => date("Y-m-d H:i:s"),"lastFollowTime" => date("Y-m-d H:i:s")),
                        "where" => " khid = '$field[targetId]' ",
                    ));
                }
            }
            $name = $kehu['companyName']??'';
            $url = "control/adIndex.html?cla=client&fun=detail&menu=clientRecord&id=".$field['targetId'];
            if ($this->post('contactId')=='frequent') {
                //客户基本信息中的联系人
                $kehuStaff['id']=$kehu['khid']??'';
                $kehuStaff['name']=$kehu['contactName']??'';
            } else {
                $kehuStaff = query('kehu_staff', "id = '{$this->post('contactId')}'");
            }

            $field['kehuStaffId'] = $kehuStaff['id'];
            $field['contactName'] = $kehuStaff['name'];
            $field['targetName'] = $kehu['companyName']??'';
            $targetCla = 'client';
            $targetFun = 'detail';
        } elseif ($field['target'] == "线索") {
            if (!$this->power("clue", "newFollow")) {
                $json['warn'] = L('follow.add.clientPower');
            } else {
                $info = query("clue", " id = '$field[targetId]' ");
                if (empty($info['id'])) {
                    $json['warn'] = L('follow.add.clueEmpty');
                } else {
                    $finger = 2;
                    //更新客户更新时间
                    update(array(
                        "table" => "clue",
                        "field" => array("updateTime" => date("Y-m-d H:i:s"),"lastFollowTime" => date("Y-m-d H:i:s")),
                        "where" => " id = '$field[targetId]' ",
                    ));
                }
            }
            $name = $info['name']??'';
            $field['targetName'] = $name;
            $url = "control/adIndex.html?cla=clue&fun=detail&menu=clueRecord&id=".$field['targetId'];
            $targetCla = 'clue';
            $targetFun = 'detail';
        } elseif ($field['target'] == "商机") {
            if (!$this->power("opportunity", "newFollow")) {
                $json['warn'] = L('follow.add.clientPower');
            } else {
                $info = query("opportunity", " id = '$field[targetId]' ");
                if (empty($info['id'])) {
                    $json['warn'] = L('follow.add.opportunityEmpty');
                } else {
                    $finger = 2;
                    //更新客户更新时间
                    update(array(
                        "table" => "opportunity",
                        "field" => array("updateTime" => date("Y-m-d H:i:s"),),
                        "where" => " id = '$field[targetId]' ",
                    ));
                }
            }
            $name = $info['name']??'';
            $field['targetName'] = $name;
            $url = "control/adIndex.html?cla=opportunity&fun=detail&menu=opportunityRecord&id=".$field['targetId'];
            $targetCla = 'opportunity';
            $targetFun = 'detail';
        } elseif ($field['target'] == "人才库") {
            if (!$this->power("talentPool", "newFollow")) {
                $json['warn'] = L('follow.add.power');
            } else {
                $talentPool = query("talent_pool", " id = '$field[targetId]' ");
                if (empty($talentPool['id'])) {
                    $json['warn'] = L('follow.add.talentEmpty');
                } else {
                    $finger = 2;
                }
                $name = $talentPool['name'];
            }
            $field['targetName'] = $name??'';
            $url = "control/adIndex.html?cla=talentPool&fun=detail&menu=talentRecord&id=".$field['targetId'];
            $targetCla = 'talentPool';
            $targetFun = 'detail';
        } elseif ($field['target'] == "供应商") {
            if (!$this->power("supplier", "edit")) {
                $json['warn'] = L('follow.add.power');
            } else {
                $info = query("supplier", " id = '$field[targetId]' ");
                if (empty($info['id'])) {
                    $json['warn'] = L('follow.add.supplierEmpty');
                } else {
                    $finger = 2;
                }
                $name = $info['name'];
            }
            $field['targetName'] = $name??'';
            $url = "control/adIndex.html?cla=supplier&fun=detail&menu=supplierRecord&id=".$field['targetId'];
            $targetCla = 'supplier';
            $targetFun = 'detail';
        } else {
            $json['warn'] = L('follow.add.objUnknown');
        }
        if ($finger == 2) {
            $warn = insert(array("table" => "follow","field" => $field));
            if ($warn == "新增成功") {
                if ($this->post('workFlow')) {
                    if ($field['target'] =='客户') {
                        update(array('table'=>'kehu','field'=>['workFlow'=>$this->post('workFlow')],'where'=>"khid = '$field[targetId]'"));
                    } elseif ($field['target'] =='线索') {
                        update(array('table'=>'clue','field'=>['workFlow'=>$this->post('workFlow')],'where'=>"id = '$field[targetId]'"));
                    } elseif ($field['target'] =='商机') {
                        update(array('table'=>'opportunity','field'=>['possibility'=>$this->post('workFlow'),'reason'=>$this->post('reason')],'where'=>"id = '$field[targetId]'"));
                    }
                }
                //结束代办事项
                backlogEnd(array("stid" => $this->control['stid'],"typeId" => $field['targetId']));
                //如果有提交下次跟进日
                if (!empty($this->post('startDay'))) {
                    $name=$name??'';
                    backlogIn(array(
                        "stid" => $this->control['stid'],
                        "type" => $backlogType,
                        "typeId" => $field['targetId'],
                        "text" => str_replace(['{{target}}','{{name}}'], [$field['target'],$name], L('follow.add.text')),
                        "startDay" => $this->post('startDay'),
                        "targetCla" => $targetCla,
                        "targetFun" => $targetFun,
                    ));
                }
                //添加日志
                $text = str_replace(['{{staffName}}','{{target}}','{{targetId}}'], [$this->control['name'],$field['target'],$field['targetId']], L('follow.add.log')).$this->post('text');
                $this->logText(array("type" => "talentPool","text" => $text));
                //返回
                $json['warn'] = 2;
                $_SESSION['warn'] = $warn;
            } else {
                $json['warn'] = $warn;
            }
            $json['href'] = root.$url;
        }
        return isset($json)?json_encode($json, 320):'';
    }
    /*客户管理-删除跟进记录*/
    public function followDel()
    {
        //赋值
        $follow = query("follow", " id = '".$this->get('id')."' ");
        //判断
        if (empty($this->get('id'))) {
            $warn = L('follow.followDel.idEmpty');
        } elseif (empty($follow['id'])) {
            $warn = L('follow.followDel.empty');
        } elseif ($follow['stid'] != $this->control['stid']) {
            $warn = L('follow.followDel.notYours');
        } elseif ($follow['target'] == "事务") {
            if (!$this->power("affair", "followDel")) {
                $warn = L('follow.followDel.power');
            }
        } elseif ($follow['target'] == "客户") {
            if (!$this->power("client", "delFollow")) {
                $warn = L('follow.followDel.power');
            }
        } elseif ($follow['target'] == "线索") {
            if (!$this->power("clue", "delFollow")) {
                $warn = L('follow.followDel.power');
            }
        } elseif ($follow['target'] == "商机") {
            if (!$this->power("opportunity", "delFollow")) {
                $warn = L('follow.followDel.power');
            }
        } elseif ($follow['target'] == "订单") {
            if (!$this->power("order", "delFollow")) {
                $warn = L('follow.followDel.power');
            }
        } elseif ($follow['target'] == "人才库") {
            if (!$this->power("talentPool", "delFollow")) {
                $warn = L('follow.followDel.power');
            }
        } else {
            $warn = L('follow.followDel.objUnknown');
        }
        if (empty($warn)) {
            $bool = delete(array("table" => "follow","where" => "id = '".$this->get('id')."'"));
            if ($bool) {
                $warn = L('follow.followDel.success');
                //删除跟进待办
                delete(array("table" => "backlog","where" => "typeId = '$follow[targetId]' and stid = '$follow[stid]' and workFlow = '待处理' and time = '$follow[time]'"));
                //添加日志
                $text = str_replace(['{{staffName}}'], [$this->control['name']], L('follow.followDel.log')).$follow['text'];
                $this->logText(array("type" => "follow","text" => $text));
            } else {
                $warn = L('follow.followDel.fail');
            }
        }
        $page = getenv("HTTP_REFERER");//传送数据过来的页面名称
        if (strstr($page, "adIndex.html?cla=affair") !== false) {
            $locationUrl = root."control/adIndex.html?cla=affair&fun=detail&menu=affairFollow&id=".$follow['targetId'];
        } elseif (strstr($page, "adIndex.html?cla=client") !== false) {
            $locationUrl = root."control/adIndex.html?cla=client&fun=detail&menu=clientRecord&id=".$follow['targetId'];
        } elseif (strstr($page, "adIndex.html?cla=clue") !== false) {
            $locationUrl = root."control/adIndex.html?cla=clue&fun=detail&menu=clueRecord&id=".$follow['targetId'];
        } elseif (strstr($page, "adIndex.html?cla=order") !== false) {
            $locationUrl = root."control/adIndex.html?cla=order&fun=detail&menu=orderRecord&id=".$follow['targetId'];
        } elseif (strstr($page, "adIndex.html?cla=talentPool") !== false) {
            $locationUrl = root."control/adIndex.html?cla=talentPool&fun=detail&menu=talentRecord&id=".$follow['targetId'];
        } else {
            $locationUrl = $page;
        }
        $_SESSION['warn'] = $warn;
        header("location:".$locationUrl);
        exit(0);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'跟进人',
                    'aliasName'=>'跟进人',
                ],
                [
                    'columnName'=>'对象名称',
                    'aliasName'=>'对象名称',
                ],
                [
                    'columnName'=>'联系人',
                    'aliasName'=>'联系人',
                ],
                [
                    'columnName'=>'跟进方式',
                    'aliasName'=>'跟进方式',
                ],
                [
                    'columnName'=>'跟进内容',
                    'aliasName'=>'跟进内容',
                ],
                [
                    'columnName'=>'跟进时间',
                    'aliasName'=>'跟进时间',
                ],
            ]
        };
    }
}
